from PyQt5.Qt import Qt
from PyQt5.QtCore import QPoint, QRect, pyqtSignal, QPointF, QEvent, QTimerEvent
from PyQt5.QtGui import QPainter, QPen, QBrush, QColor, QFont, QWheelEvent, QMouseEvent, QFontMetrics
from PyQt5.QtWidgets import QWidget, QScrollArea, QCheckBox, QDialog

from utils.labelsample.ui.setclassdialog import SetClassDialog
from utils.labelsample.ui_gen.sampleviewer_impl import Ui_Form
import numpy as np

from utils.csi_data import CSI_Data
from utils.csi_detail import get_phase_dif_single
from utils.csi_detail import CSI_Seq
from utils.csi_detail import getDetail
import sys

from utils.lbl_data import LblData


class SampleViewer(QWidget, Ui_Form):
    xscalechanged = pyqtSignal(bool, QPointF, float)

    IDLE = 0
    PREADD = 1
    ADD = 2
    RLEFT = 3
    RRIGHT = 4

    def __init__(self, parent=None):
        super(QWidget, self).__init__(parent)
        self.setupUi(self)
        self.init()

    def init(self):
        self.setMouseTracking(True)
        self.state = self.IDLE
        self.addColor = QColor('#40000000')
        self.regionColors = [QColor('#60F61B00'), QColor('#60FEFF29'), QColor('#601B00FC'),
                             QColor('#60F99017'), QColor('#6050FF29'), QColor('#607B00FD')]
        self.maxRegion = len(self.regionColors) - 1
        self.addX1 = -1
        self.addX2 = -1
        self.regions = []
        self.regionDragWidth = 10
        self.readyDelete = False
        self.readyChangeClass = False
        self.demo = True
        self.demosamplepersec = 100
        self.xscalepersecdelta = 10
        self.xscalepersec = 80
        self.xscalepersecmin = 20
        self.xscalepersecmax = 600
        self.xscalepersecdemo = 60
        self.xscalepersecdemomin = 10
        self.xscalepersecdemomax = 600
        self.axisScaleHeight = 6
        self.totalTime = 100
        self.axisXTextWidth = 100
        self.axisXTextHeight = 20
        self.demoymax = 100
        self.plotcolor = QColor(Qt.red)
        self.maxysegcnt = 100
        self.yaxismargin = 80
        self.yaxisoffset = 0
        self.ymargin = 30
        self.ytextmargin = 10
        self.xaxisbase = 0
        self.yprecision = 4
        self.yseg(8)
        if self.demo:
            self.ylim(-np.pi, np.pi)
        else:
            self.ylim(0, np.pi)
        self.setMouseTracking(True)
        self.showHintTimer = -1
        self.showHint = False
        self.hoverTime = 300

    def setMainWindow(self, window):
        self.mainwindow = window

    def paintEvent(self, _):
        painter = QPainter()
        painter.begin(self)
        painter.setRenderHint(QPainter.Antialiasing)

        # 绘制背景
        painter.fillRect(self.rect(), Qt.white)

        # 绘制主轴
        painter.drawLine(self.yaxismargin + self.yaxisoffset, 0, self.yaxismargin + self.yaxisoffset,
                         self.rect().height())
        painter.drawLine(0, self.xaxisbase, self.rect().width(), self.xaxisbase)

        # 绘制X坐标
        if self.demo:
            pass
        else:
            painter.save()
            painter.setClipRect(self.yaxisoffset + self.yaxismargin, 0, self.holder.width(), self.height())
            penscalex = QPen(Qt.black, 2)
            pentextx = QPen(Qt.black, 1)
            painter.setPen(penscalex)
            if self.xscalepersec > 50:
                for i in range(1, int(self.totalTime) + 1):
                    painter.setPen(penscalex)
                    painter.drawLine(i * self.xscalepersec + self.yaxismargin,
                                     self.xaxisbase - self.axisScaleHeight,
                                     i * self.xscalepersec + self.yaxismargin, self.xaxisbase)
                    painter.setPen(pentextx)
                    painter.drawText(
                        QRect(i * self.xscalepersec + self.yaxismargin - self.axisXTextWidth / 2, self.xaxisbase,
                              self.axisXTextWidth, self.axisXTextHeight),
                        Qt.AlignCenter, "%ds" % i)
            else:
                for i in range(2, int(self.totalTime) + 1, 2):
                    painter.setPen(penscalex)
                    painter.drawLine(i * self.xscalepersec + self.yaxismargin,
                                     self.xaxisbase - self.axisScaleHeight,
                                     i * self.xscalepersec + self.yaxismargin, self.xaxisbase)
                    painter.setPen(pentextx)
                    painter.drawText(
                        QRect(i * self.xscalepersec + self.yaxismargin - self.axisXTextWidth / 2, self.xaxisbase,
                              self.axisXTextWidth, self.axisXTextHeight),
                        Qt.AlignCenter, "%ds" % i)
            if 100 <= self.xscalepersec < 300:
                for i in range(0, int(self.totalTime) + 1):
                    painter.setPen(penscalex)
                    painter.drawLine(i * self.xscalepersec + self.yaxismargin + self.xscalepersec / 2,
                                     self.xaxisbase - self.axisScaleHeight,
                                     i * self.xscalepersec + self.yaxismargin + self.xscalepersec / 2, self.xaxisbase)
                    painter.setPen(pentextx)
                    painter.drawText(
                        QRect(
                            i * self.xscalepersec + self.yaxismargin - self.axisXTextWidth / 2 + self.xscalepersec / 2,
                            self.xaxisbase,
                            self.axisXTextWidth, self.axisXTextHeight),
                        Qt.AlignCenter, "%.1fs" % (i + 0.5))
            elif 300 <= self.xscalepersec < 500:
                for i in range(0, int(self.totalTime) + 1):
                    for j in range(4):
                        painter.setPen(penscalex)
                        painter.drawLine(i * self.xscalepersec + self.yaxismargin + (j + 1) * self.xscalepersec / 5,
                                         self.xaxisbase - self.axisScaleHeight,
                                         i * self.xscalepersec + self.yaxismargin + (j + 1) * self.xscalepersec / 5,
                                         self.xaxisbase)
                        painter.setPen(pentextx)
                        painter.drawText(
                            QRect(
                                i * self.xscalepersec + self.yaxismargin - self.axisXTextWidth / 2 + (
                                        j + 1) * self.xscalepersec / 5,
                                self.xaxisbase,
                                self.axisXTextWidth, self.axisXTextHeight),
                            Qt.AlignCenter, "%.1fs" % (i + (j + 1) / 5))
            elif 500 <= self.xscalepersec:
                for i in range(0, int(self.totalTime) + 1):
                    for j in range(9):
                        painter.setPen(penscalex)
                        painter.drawLine(i * self.xscalepersec + self.yaxismargin + (j + 1) * self.xscalepersec / 10,
                                         self.xaxisbase - self.axisScaleHeight,
                                         i * self.xscalepersec + self.yaxismargin + (j + 1) * self.xscalepersec / 10,
                                         self.xaxisbase)
                        painter.setPen(pentextx)
                        painter.drawText(
                            QRect(
                                i * self.xscalepersec + self.yaxismargin - self.axisXTextWidth / 2 + (
                                        j + 1) * self.xscalepersec / 10,
                                self.xaxisbase,
                                self.axisXTextWidth, self.axisXTextHeight),
                            Qt.AlignCenter, "%.1fs" % (i + (j + 1) / 10))
            painter.restore()
            # 绘制Y坐标
            if self.demo:
                pass
            else:
                penscalex = QPen(Qt.black, 2)
                pentextx = QPen(Qt.black, 1)
                height = self.height() - 2 * self.ymargin
                painter.setPen(penscalex)
                for i in range(self.ysegcnt + 1):
                    if (np.abs(self.ymargin + height * i / self.ysegcnt - self.xaxisbase)) > height / self.ysegcnt / 5:
                        painter.drawLine(self.yaxismargin + self.yaxisoffset, self.ymargin + height * i / self.ysegcnt,
                                         self.yaxismargin + self.yaxisoffset + self.axisScaleHeight,
                                         self.ymargin + height * i / self.ysegcnt)
                painter.setPen(pentextx)
                value = [self.ymax - (self.ymax - self.ymin) * i / self.ysegcnt for i in range(self.ysegcnt + 1)]
                mdig = self.maxdig(value)
                pattern = "{0:>.%df}" % mdig
                for i in range(self.ysegcnt + 1):
                    if (np.abs(self.ymargin + height * i / self.ysegcnt - self.xaxisbase)) > height / self.ysegcnt / 5:
                        rect = QRect(self.yaxisoffset, self.ymargin + (height * (i - 0.5)) / self.ysegcnt,
                                     self.yaxismargin - self.ytextmargin,
                                     height / self.ysegcnt)
                        painter.drawText(rect, Qt.AlignRight | Qt.AlignVCenter, pattern.format(value[i]))

        # 绘制区域

        for i in range(len(self.regions)):
            lbldat = self.regions[i]  # type:LblData
            x1 = self.timeToXPos(lbldat.startTime)
            x2 = self.timeToXPos(lbldat.endTime)
            painter.save()
            painter.setBrush(QBrush(self.regionColors[lbldat.type]))
            painter.setPen(QPen(Qt.darkGray))
            painter.setClipRect(self.yaxisoffset + self.yaxismargin, 0, self.holder.width(), self.height())
            painter.drawRect(QRect(x1, 5, x2 - x1, self.height() - 10))
            painter.setPen(QPen(Qt.white))
            painter.drawLine(x1 + self.regionDragWidth, 6, x1 + self.regionDragWidth, self.height() - 6)
            painter.drawLine(x2 - self.regionDragWidth, 6, x2 - self.regionDragWidth, self.height() - 6)
            painter.restore()

        if self.state == self.PREADD or self.state == self.ADD:
            painter.save()
            painter.setBrush(self.addColor)
            painter.setPen(QPen(Qt.darkGray))
            painter.setClipRect(self.yaxisoffset + self.yaxismargin, 0, self.holder.width(), self.height())
            x1 = self.addX1
            x2 = self.addX2
            if x1 < x2:
                t = x1
                w = x2 - x1
            else:
                t = x2
                w = x1 - x2
            painter.drawRect(QRect(t, 5, w, self.height() - 10))
            painter.restore()

        # 绘制波形
        painter.setPen(QPen(QBrush(self.plotcolor), 1))
        if self.demo:
            width = self.width() - self.yaxismargin
            cnt = width / self.xscalepersecdemo + 1

            for i in range((int(cnt) + 1) * self.demosamplepersec):
                painter.drawLine(self.yaxismargin + i * self.xscalepersecdemo / self.demosamplepersec,
                                 self.xaxisbase - self.demoymax * np.sin(i * np.pi / self.demosamplepersec),
                                 self.yaxismargin + (
                                         i + 1) * self.xscalepersecdemo / self.demosamplepersec,
                                 self.xaxisbase - self.demoymax * np.sin((i + 1) * np.pi / self.demosamplepersec))
            painter.save()
            font = painter.font()  # type:QFont
            font.setPointSize(np.min([self.width(), self.height()]) // 8)
            painter.setFont(font)
            painter.setPen(QPen(Qt.blue))
            painter.drawText(self.rect(), Qt.AlignCenter, 'This is a demo!')
            painter.restore()
        else:
            self.drawCSI(painter)

        # 绘制提示

        if not self.demo and self.showHint:
            time = (self.mouseHoverPos.x() - self.yaxismargin) / self.xscalepersec
            tmp = self.height() - 2 * self.ymargin
            value = self.ymin + (self.height() - self.mouseHoverPos.y() - self.ymargin) * (self.ymax - self.ymin) / tmp
            txt = '  {0:.2f}s {1:.4f}  '.format(time, value)
            fontmet = painter.fontMetrics()  # type:QFontMetrics
            width = fontmet.boundingRect(txt).width()
            height = fontmet.boundingRect(txt).height()
            if width + self.mouseHoverPos.x() - self.holder.horizontalScrollBar().value() < self.holder.width():
                if height + self.mouseHoverPos.y() < self.holder.height() - 30:
                    txtrect = QRect(self.mouseHoverPos.x(), self.mouseHoverPos.y(), width, height)
                else:
                    txtrect = QRect(self.mouseHoverPos.x(), self.mouseHoverPos.y() - height, width, height)
            else:
                if height + self.mouseHoverPos.y() < self.holder.height() - 30:
                    txtrect = QRect(self.mouseHoverPos.x() - width, self.mouseHoverPos.y(), width, height)
                else:
                    txtrect = QRect(self.mouseHoverPos.x() - width, self.mouseHoverPos.y() - height, width, height)

            painter.setPen(QPen(Qt.transparent))
            painter.setBrush(QBrush(QColor('#80000000')))
            painter.drawRect(txtrect)
            painter.setPen(QPen(Qt.white))
            painter.drawText(txtrect, Qt.AlignLeft, txt)
            painter.setPen(QPen(Qt.red))
            painter.setBrush(QBrush(Qt.transparent))
            painter.drawLine(self.mouseHoverPos.x(), self.mouseHoverPos.y() - 5, self.mouseHoverPos.x(),
                             self.mouseHoverPos.y() + 5)
            painter.drawLine(self.mouseHoverPos.x() - 5, self.mouseHoverPos.y(), self.mouseHoverPos.x() + 5,
                             self.mouseHoverPos.y())
        painter.end()

    def xPosToTime(self, x):
        return (x - self.yaxismargin) / self.xscalepersec

    def timeToXPos(self, time):
        return int(time * self.xscalepersec + self.yaxismargin)

    def adaptWidth(self, max):
        if self.demo:
            width = max - 2  # don't draw horizontal scrollbar
        else:
            width = self.yaxismargin + (self.totalTime + 1) * self.xscalepersec
            if width < max:
                width = max
        self.setFixedWidth(width)

    def wheelEvent(self, event: QWheelEvent):
        point = event.angleDelta()  # type:QPoint
        if point.y() > 0:
            self.setXScalePerSecDelta(self.xscalepersecdelta, event)
            self.setXScalePerSecDemoDelta(self.xscalepersecdelta)
        else:
            self.setXScalePerSecDelta(-self.xscalepersecdelta, event)
            self.setXScalePerSecDemoDelta(-self.xscalepersecdelta)
        if self.showHintTimer != -1:
            self.killTimer(self.showHintTimer)
        self.showHint = False
        self.update()

    def ylim(self, minv, maxv):
        height = self.height() - 2 * self.ymargin
        if maxv > minv:
            self.ymin = minv
            self.ymax = maxv
            temp = height / (maxv - minv)
            self.xaxisbase = self.height() - self.ymargin + temp * minv
            if self.xaxisbase < self.ymargin:
                self.xaxisbase = self.ymargin
            elif self.xaxisbase > self.height() - self.ymargin:
                self.xaxisbase = self.height() - self.ymargin
            self.update()

    def setXScalePerSecDemoDelta(self, x):
        tmp = self.xscalepersecdemo + x
        if tmp > self.xscalepersecdemomax:
            tmp = self.xscalepersecdemomax
        elif tmp < self.xscalepersecdemomin:
            tmp = self.xscalepersecdemomin
        self.xscalepersecdemo = tmp
        self.update()

    def setXScalePerSecDelta(self, x, event):
        tmp = self.xscalepersec + x
        if tmp > self.xscalepersecmax:
            tmp = self.xscalepersecmax
        elif tmp < self.xscalepersecmin:
            tmp = self.xscalepersecmin
        d = tmp * self.width() / self.xscalepersec
        self.xscalepersec = tmp
        self.xscalechanged.emit(self.demo, event.posF(), d)

    def setyoffset(self, offset):
        self.yaxisoffset = 0 if offset < 0 else offset
        self.update()

    def maxdig(self, arr: list):
        dig = 0
        for i in range(len(arr)):
            d = self.getdig(arr[i])
            if d > dig:
                dig = d
        return dig

    def getdig(self, i):
        ret = 0
        i = round(i, self.yprecision)
        j = str(i)
        t = j.split(r'.')
        l = len(t)
        if l > 1:
            ret += 1
            t = t[1]
        else:
            return ret
        k = len(t) - 1
        while t[k] != '0' and k > 0:
            k -= 1
            ret += 1
        return ret

    def yseg(self, i):
        if 0 < i <= self.maxysegcnt:
            self.ysegcnt = i
        elif i > self.maxysegcnt:
            self.ysegcnt = self.maxysegcnt
        else:
            self.ysegcnt = 0
        self.update()

    def timerEvent(self, event: QTimerEvent):
        if event.timerId() == self.showHintTimer:
            self.killTimer(self.showHintTimer)
            self.showHintTimer = -1
            self.showHint = True
            self.update()

    def leaveEvent(self, QEvent):
        self.showHint = False
        if self.showHintTimer != -1:
            self.killTimer(self.showHintTimer)
            self.showHintTimer = -1
            self.update()

    def setHolder(self, holder: QScrollArea):
        self.holder = holder

    def mousePressEvent(self, event: QMouseEvent):
        self.showHint = False
        if event.button() == Qt.LeftButton:
            inRegions, idx = self.checkMousePressInRegions(event.pos())
            if not inRegions:
                self.state = self.PREADD
                self.addX1 = event.pos().x()
                self.addX2 = self.addX1
            else:
                bound = self.get_region_bound(idx, event.x())
                if bound == 0:
                    self.readyChangeClass = True
                    self.changeIdx = idx
                elif bound == -1:
                    self.state = self.RLEFT
                    self.tmpIdx = idx
                    self.tmpMouseX = event.x()
                    self.tmpBound = self.timeToXPos(self.regions[idx].startTime)
                else:
                    self.state = self.RRIGHT
                    self.tmpIdx = idx
                    self.tmpMouseX = event.x()
                    self.tmpBound = self.timeToXPos(self.regions[idx].endTime)
        elif event.button() == Qt.RightButton:
            inRegions, idx = self.checkMousePressInRegions(event.pos())
            if inRegions:
                self.readyDelete = True
                self.deleteIdx = idx
        #     self.regions.sort(key=lambda x:x.startTime)
        self.update()

    def mouseReleaseEvent(self, event: QMouseEvent):
        if self.state == self.PREADD:
            if not self.demo and np.abs(self.xPosToTime(self.addX1) - self.xPosToTime(self.addX2)) >= 0.2:
                self.state = self.ADD
                dialog = SetClassDialog(self.maxRegion)
                dialog.exec()
                if dialog.ok:
                    c = dialog.value
                    if self.addX2 > self.addX1:
                        t1 = self.xPosToTime(self.addX1)
                        t2 = self.xPosToTime(self.addX2)
                    else:
                        t1 = self.xPosToTime(self.addX2)
                        t2 = self.xPosToTime(self.addX1)
                    dat = LblData()
                    dat.startTime = t1
                    dat.endTime = t2
                    dat.type = c
                    self.regions.append(dat)
                    self.regions.sort(key=lambda x: x.startTime)
            self.state = self.IDLE
        if self.state == self.RLEFT or self.state == self.RRIGHT:
            self.state = self.IDLE

        if self.readyDelete:
            self.readyDelete = False
            inRegions, idx = self.checkMousePressInRegions(event.pos())
            if inRegions and idx == self.deleteIdx:
                self.regions = self.regions[:idx] + self.regions[idx + 1:]
        if self.readyChangeClass:
            self.readyChangeClass = False
            inRegions, idx = self.checkMousePressInRegions(event.pos())
            if inRegions and idx == self.changeIdx:
                dialog = SetClassDialog(self.maxRegion)
                dialog.setValue(self.regions[idx].type)
                dialog.exec()
                if dialog.ok:
                    self.regions[idx].type = dialog.value
        self.update()

    def mouseMoveEvent(self, event: QMouseEvent):
        if event.button() is not Qt.LeftButton:
            self.showHint = False
            if self.showHintTimer != -1:
                self.killTimer(self.showHintTimer)
            self.mouseHoverPos = event.pos()
            self.showHintTimer = self.startTimer(self.hoverTime)
        if self.state == self.PREADD:
            self.addX2 = event.pos().x()
            lidx = self.findLeftRegion(self.addX1)
            if lidx != -1:
                x = self.timeToXPos(self.regions[lidx].endTime)
                if self.addX2 < x + 5:
                    self.addX2 = x + 5
            ridx = self.findRightRegion(self.addX1)
            if ridx != -1:
                x = self.timeToXPos(self.regions[ridx].startTime)
                if self.addX2 > x - 5:
                    self.addX2 = x - 5
        if self.state == self.RLEFT:
            mousex = event.x()
            t = mousex - self.tmpMouseX
            ldat = self.regions[self.tmpIdx]  # type:LblData
            x2 = self.timeToXPos(ldat.endTime)
            tmp = self.tmpBound + t
            if tmp > x2 - self.regionDragWidth * 2:
                tmp = x2 - self.regionDragWidth * 2
            left = self.findLeftRegion(self.timeToXPos(ldat.endTime))
            if left > 0:
                tmp2 = self.timeToXPos(self.regions[left - 1].endTime)
                if tmp < tmp2:
                    tmp = tmp2
            ldat.startTime = self.xPosToTime(tmp)
        if self.state == self.RRIGHT:
            mousex = event.x()
            t = mousex - self.tmpMouseX
            ldat = self.regions[self.tmpIdx]  # type:LblData
            x2 = self.timeToXPos(ldat.startTime)
            tmp = self.tmpBound + t
            if tmp < x2 + self.regionDragWidth * 2:
                tmp = x2 + self.regionDragWidth * 2
            right = self.findRightRegion(self.timeToXPos(ldat.startTime))
            if right != -1 and right < len(self.regions) - 1:
                tmp2 = self.timeToXPos(self.regions[right + 1].startTime)
                if tmp > tmp2:
                    tmp = tmp2
            ldat.endTime = self.xPosToTime(tmp)
            self.update()

    def findLeftRegion(self, x):
        ret = -1
        for i in range(len(self.regions)):
            lbldat = self.regions[i]  # type:LblData
            x2 = self.timeToXPos(lbldat.endTime)
            if x2 <= x:
                ret = i
            if ret >= len(self.regions):
                ret = -1
                break
        return ret

    def findRightRegion(self, x):
        ret = len(self.regions)
        for i in range(len(self.regions) - 1, -1, -1):
            lbldat = self.regions[i]  # type:LblData
            x2 = self.timeToXPos(lbldat.startTime)
            if x2 >= x:
                ret = i
        if ret >= len(self.regions):
            ret = -1
        return ret

    def checkMousePressInRegions(self, pos: QPoint):
        for i in range(len(self.regions)):
            lbldat = self.regions[i]  # type:LblData
            x1 = self.timeToXPos(lbldat.startTime)
            x2 = self.timeToXPos(lbldat.endTime)
            if x1 <= pos.x() <= x2:
                return True, i
        return False, -1

    def setCSIDetail(self, csi_detail):
        self.demo = False
        self.state = self.IDLE
        self.regions = []
        self.csi_detail = csi_detail
        self.totalTime = self.csi_detail.totalTime
        self.adaptWidth(self.holder.width())

    def onMainWindowOptionChanged(self, type, csinum, antsend, ant1, ant2):

        self.type = type
        self.antsend = antsend
        self.csinum = csinum
        self.ant1 = ant1
        self.ant2 = ant2
        self.update()

    def drawCSI(self, painter: QPainter):
        if self.csi_detail is not None:
            painter.save()
            painter.setClipRect(self.yaxisoffset + self.yaxismargin, 0, self.holder.width(), self.height())
            if self.type == 0:  # 幅值
                data = self.csi_detail.amplitude[self.antsend - 1][self.ant1 - 1][self.csinum - 1]
                self.plotAll(painter, data)
            elif self.type == 1:  # 相位
                data = self.csi_detail.phase[self.antsend - 1][self.ant1 - 1][self.csinum - 1]
                self.plotAll(painter, data)
            elif self.type == 2:  # 幅度差
                data = self.csi_detail.amplitudedif[self.antsend - 1][self.ant1 - 1][self.ant2 - 1][self.csinum - 1]
                self.plotAll(painter, data)
                pass
            elif self.type == 3:  # 相位差
                data = self.csi_detail.phasedif[self.antsend - 1][self.ant1 - 1][self.ant2 - 1][self.csinum - 1]
                self.plotAll(painter, data)
            painter.restore()
        self.update()

    def plotAll(self, painter, data):
        if len(data) < self.csi_detail.totalCnt / 100:  # Less than 1 percent,consider not valid
            font = painter.font()
            font.setPointSize(self.height() / 5)
            painter.setFont(font)
            painter.drawText(
                QRect(self.yaxismargin + self.yaxisoffset, 0, self.holder.width() - self.yaxismargin,
                      self.height()), Qt.AlignCenter, '没有该项数据!')
        else:
            chb = self.mainwindow.cbFixYlim  # type:QCheckBox
            if chb.isChecked():
                min = self.mainwindow.dsbYlimmin.value()
                max = self.mainwindow.dsbYlimmax.value()
            else:
                min = self.getCSISeqMin(data)
                max = self.getCSISeqMax(data)
            self.ylim(min, max)
            for i in range(len(data) - 1):
                self.plotTwo(painter, data[i], data[i + 1])

    def getCSISeqMin(self, data):
        min = sys.maxsize
        for i in range(len(data)):
            if data[i].value < min:
                min = data[i].value
        return min

    def getCSISeqMax(self, data):
        max = -sys.maxsize
        for i in range(len(data)):
            if data[i].value > max:
                max = data[i].value
        return max

    def plotTwo(self, painter, seq1: CSI_Seq, seq2: CSI_Seq):
        p1 = self.seqToPoint(seq1)
        p2 = self.seqToPoint(seq2)
        painter.drawLine(p1, p2)

    def seqToPoint(self, seq):
        value = seq.value
        time = seq.time
        x = self.yaxismargin + time * self.xscalepersec
        tmp = self.height() - 2 * self.ymargin
        y = self.ymargin + (self.ymax - value) * tmp / (self.ymax - self.ymin)
        return QPointF(x, y)

    def get_region_bound(self, idx, x):
        region = self.regions[idx]  # type:LblData
        x1 = self.timeToXPos(region.startTime) + 10
        x2 = self.timeToXPos(region.endTime) - 10
        if x < x1:
            return -1
        elif x > x2:
            return 1
        else:
            return 0


